package com.scm.biz.service._impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.scm.biz.bean.CustomerContact;
import com.scm.biz.dao.CustomerContactDao;
import com.scm.biz.service.CustomerContactService;
import com.scm.core.bean.exp.UfdmException;
import com.scm.utils.Const;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("customerContactService")
public class CustomerContactServiceImpl implements CustomerContactService{
	
	@Resource
	private CustomerContactDao customerContactDao;
	
	@Override
	public void save(String contacts,long customerId) throws UfdmException {
		if(contacts==null||contacts.trim().isEmpty()){
			throw new UfdmException("联系人为空");
		}
		JSONArray jsonArray=JSONArray.fromObject(contacts);
		@SuppressWarnings("unchecked")
		Iterator<JSONObject> it=jsonArray.iterator();
		while(it.hasNext()){
			JSONObject object=it.next();
			CustomerContact contact=new CustomerContact(object);
			if(contact.getLinkman()==null||contact.getLinkman().trim().isEmpty()){
				throw new UfdmException("联系人名为空");
			}
			if(contact.getContact()==null||contact.getContact().trim().isEmpty()){
				throw new UfdmException("联系方式为空");
			}
			if(!contact.getContact().matches(Const.CONTACT)){
				throw new UfdmException("联系方式格式不符");
			}
			if(contact.getEmail()!=null&&!contact.getEmail().trim().isEmpty()){
				if(!contact.getEmail().matches(Const.EMAIL)){
					throw new UfdmException("联系邮箱格式不符");
				}
			}
			contact.setCustomerId(customerId);
			contact.setCreateAt(new Date());
			customerContactDao.insert(contact);
		}
	}

	@Override
	public int modifyById(CustomerContact contact) {
		contact.setUpdateAt(new Date(System.currentTimeMillis()));
		return customerContactDao.updateByPrimaryKey(contact);
	}

	@Override
	public int removeById(int id) {
		return customerContactDao.deleteByPrimaryKey(id);
	}

	@Override
	public List<CustomerContact> selectListByCustomerId(int customerId) {
		return customerContactDao.selectListByCustomerId(customerId);
	}

	@Override
	public int removeByCustomerId(int customerId) {
		return customerContactDao.deleteByCustomerId(customerId);
	}
	
	
}
